#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 12345
#define MAX_BUFFER 1024

// 定义词典内容
typedef struct {
    char *english;
    char *chinese;
} Dictionary;

Dictionary dict[] = {
    {"mooncake", "月饼"},
    {"festival", "节日"},
    {"operation", "操作"},
    {"system", "系统"},
    {"file", "文件"}
};
#define DICT_SIZE (sizeof(dict) / sizeof(dict[0]))

// 英汉互译功能
const char* translate_bidirectional(const char *word) {
    for (int i = 0; i < DICT_SIZE; i++) {
        if (strcmp(dict[i].english, word) == 0) {
            return dict[i].chinese;  // 英译汉
        }
        if (strcmp(dict[i].chinese, word) == 0) {
            return dict[i].english;  // 汉译英
        }
    }
    return "未找到该单词的翻译";
}

int main() {
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t addr_len = sizeof(client_addr);
    char buffer[MAX_BUFFER];

    // 创建socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("无法创建socket");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定socket
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("绑定失败");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 3) < 0) {
        perror("监听失败");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("服务器启动，等待客户端连接...\n");

    // 接受客户端连接
    if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) < 0) {
        perror("接受连接失败");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("客户端连接成功\n");

    // 接收客户端请求并返回翻译
    while (1) {
        memset(buffer, 0, MAX_BUFFER);
        int bytes_received = recv(client_fd, buffer, MAX_BUFFER, 0);
        if (bytes_received <= 0) {
            break;
        }
        printf("收到客户端请求：%s\n", buffer);
        const char *translation = translate_bidirectional(buffer);
        send(client_fd, translation, strlen(translation), 0);
    }

    printf("客户端断开连接\n");
    close(client_fd);
    close(server_fd);
    return 0;
}
